const express = require("express");
const pool = require("../pool");
const log = require("../log");

const router = express.Router();

// 登录路由
router.post("/login", (req, res) => {
	let obj = req.body;
	log.info('登陆操作', obj);
	sql = "select upwd from users where uname = ?";
	pool.query(sql, obj.uname, (err, data) => {
		if(err !== null) {
			log.error('登录sql查询错误', err);
			return;
		}
		if (data.length >= 1 && data[0].upwd === obj.upwd) {
			res.send({ code: 200, msg: "登录成功" });
		} else {
			res.send({ code: 300, mag: "登录失败：密码或用户名不正确" });
		}
	});
});

// 注册路由
router.post("/reg", (req, res) => {
	let obj = req.body;
	sqlSearch = "select uname from users where uname = ?";
	pool.query(sqlSearch, obj.uname, (err, data) => {
		if (!data.length) {
			sql = "insert into users set ?";
			pool.query(sql, obj, (err, data) => {
				if (data.affectedRows) {
					res.send({ code: 201, msg: "注册成功" });
				}
			});
		} else {
			res.send({ code: 301, msg: "注册失败：用户名已存在" });
		}
	});
});

module.exports = router;
